<?php
class Apps_Controller_Action extends Zend_Controller_Action {
	const MSG_CLASS_ERROR   = 'alert-error';
	const MSG_CLASS_SUCCESS = 'alert-success';
	const MSG_CLASS_INFO 	= 'alert-info';
	const MSG_CLASS_WARNING = 'alert-warning';
	const MSG_CLASS_NOCLASS = '';

	public static $msgUpdateSuccess = array(self::MSG_CLASS_SUCCESS => 'Cập nhật dữ liệu thành công!');
	public static $msgUpdateFailed  = array(self::MSG_CLASS_ERROR   => 'Cập nhật dữ liệu không thành công.');
	public static $msgAddSuccess    = array(self::MSG_CLASS_SUCCESS => 'Cập nhật dữ liệu  thành công!');
	public static $msgAddFailed     = array(self::MSG_CLASS_ERROR   => 'Cập nhật dữ liệu không thành công.');
	public static $msgDeleteSuccess = array(self::MSG_CLASS_SUCCESS => 'Cập nhật dữ liệu thành công!');
	public static $msgDeleteError   = array(self::MSG_CLASS_ERROR   => 'Cập nhật dữ liệu không thành công.');
	public static $msgUnknownError  = array(self::MSG_CLASS_ERROR   => 'Có lỗi xảy ra, xin vui lòng thử lại.');
	public static $msgNoRecordFound = array(self::MSG_CLASS_ERROR   => 'Không tìm thấy dữ liệu.');
	public static $msgMalformData   = array(self::MSG_CLASS_ERROR   => 'Dữ liệu không hợp lệ.');
	
	protected $_namespaceRequestedParams = 'App.Paper';

    protected $_allowBacktrack = false;
    protected $_flashMessenger;
	protected $_dbAdapter;
	protected $_auth;

	protected $_page_title         = 'Viet Center Tourist';
	protected $_page_meta_keywords = 'Viet Center Tourist, viet center tourist, VietCenter Tourist, vietcenter tourist, Vct, vct, VCTOURIST, vctourist, Travel, Hotels & Tours, Tour booking, Package Tour for Vietnam, Laos, Cambodia, vc, vc tourist, visa, ticket, flight, hotel, hacongtung, ha cong tung, du lich, le hoi, hoi thao, su kien, thiet bi, mc, ca si, hoi cho, hoi nghi';
	protected $_page_meta_description = 'Cung cấp các tour du lịch trong nước và các nước Lao, Cambodia, các dịch vụ visa';


	/* DISPATCH OVERWRITTEN */
		final public function init() {
             $this->_auth = Zend_Auth::getInstance();
             if (!$this->_auth->hasIdentity() && $this->_request->getActionName() != 'login') {
//                 $this->saveRequestedParams();
//             	$this->_redirect('/system/auth/login');
             }
             
            // Get default db adapter
			$this->_dbAdapter = Zend_Db_Table::getDefaultAdapter();

			$rq = $this->_request;

			// Init flash messenger
	        $this->_flashMessenger = new Zend_Controller_Action_Helper_FlashMessenger();

			$this->_allowBacktrack = !$rq->isXmlHttpRequest();

	        $this->_init(); // Call to-be-extented method
		}
		public function preDispatch() {
			$this->view->app_backtrackUrl = $this->getBacktrackUrl();

			$rq = $this->_request;
			$this->view->app_action     = $rq->getActionName();
			$this->view->app_controller = $rq->getControllerName();
			$this->view->app_module     = $rq->getModuleName();

			$this->_preDispatch(); // Call to-be-extented method
		}
        final public function postDispatch() {
            // Save Backtrack URL - used in Requested
            if($this->_allowBacktrack) { $this->saveRequestedParams();}

            // Set page
            $view = $this->view;

            // Set meta
            if($this->_request->getActionName() != 'detail') {
                $tbVctSetting = new M_DbTable_VctSetting();
                $vctSetting   = $tbVctSetting->getMetaTag();

                $this->_page_title    = ($this->_request->getModuleName() == 'default')
                                        ? ($vctSetting['header_title'] ? $vctSetting['header_title'] : $this->_page_title)
                                        : "";

                $this->_page_meta_keywords    = ($this->_request->getModuleName() == 'default')
                                                ? ($vctSetting['meta_keyword'] ? $vctSetting['meta_keyword'] : $this->_default_keyword )
                                                : "";
                $this->_page_meta_description = ($this->_request->getModuleName() == 'default')
                                                ? ($vctSetting['meta_description'] ? $vctSetting['meta_description'] : $this->_default_description)
                                                : "";
            }

            $view->headTitle($this->_page_title);
            $view->headMeta()->setName('keywords'   , $this->_page_meta_keywords);
            $view->headMeta()->setName('description', $this->_page_meta_description);

            // Call to-be-extented method
            $this->__postDispatch();
            $this->_postDispatch();
        }

		/* To be extended by subclass (instead of original public methods) */
		protected function _init() {}
	    protected function _preDispatch(){}
		protected function _postDispatch(){}

	/* BACK TRACKING
	 *  Used to save request params
	 *     for tracing back (especially in back-button)
	 */
	    public function saveRequestedParams($v='requestedUrlParams', $namespace=null) {
	    	if(!$namespace) { $namespace = $this->_namespaceRequestedParams; }

	        $customerSession = new Zend_Session_Namespace($namespace);
	        $customerSession->$v = $this->_request->getParams();

	        return $this;
	    }
	    public function loadRequestedParams($v='requestedUrlParams', $namespace=null) {
	        if(!$namespace) { $namespace = $this->_namespaceRequestedParams; }

	    	$customerSession = new Zend_Session_Namespace($namespace);
	        return isset($customerSession->$v)
	               ? $customerSession->$v
	               : array();
	    }

	    /** Shortcut for getting Requested params url */
	    public function getBacktrackUrl($namespace=null) {
	        $params = $this->loadRequestedParams('requestedUrlParams', $namespace);

	        // Prevent loop forever
	        if($params == $this->_request->getParams()) {
	            $params = array();
	        }

	        return $this->view->url($params);
	    }
	    public function disallowBacktrack() {
	    	$this->_allowBacktrack = false;
	    	return $this;
	    }
	    public function allowBacktrack() {
	    	$this->_allowBacktrack = true;
	    	return $this;
	    }

	    public function goBack() {
	        return $this->_redirect($this->getBacktrackUrl());
	    }
	    public function goToActionIndex() {
	        return $this->_helper->redirector('index');
	    }
	    public function goToControllerIndex() {
	        return $this->_helper->redirector('index', 'index');
	    }

    /* HELPER */
    public function refresh($params=array()) {
    	$rq = $this->_request;

    	return $this->_helper->redirector(
    	           $rq->getActionName(),
    	           $rq->getControllerName(),
    	           $rq->getModuleName(),
    	           $params);
    }
    public function disableLayout($disableLayout=null, $disableView=null) {
    	if($disableLayout === true) {
    		$this->_helper->layout()->disableLayout();
    	} else if($disableLayout === false) {
    		$this->_helper->layout()->enableLayout();
    	}
    	if($disableView === true) {
    		$this->_helper->viewRenderer->setNoRender(true);
    	} else if($disableView === false) {
    		$this->_helper->viewRenderer->setNoRender(false);
    	}
    }
    public function ajaxOnly($disableLayout=true, $disableView=true) {
        if(!$this->_request->isXmlHttpRequest()) {
            $this->_redirect('/');
        }
        $this->disableLayout($disableLayout, $disableView);
    }
    public function ajaxRefresh($url=null, $msg=null) {
        if(null == $url) {
            $url = $this->getBacktrackUrl();
        }
        if(null == $msg) {
            $msg = 'Update successfully, please wait ...';
        }
        // Send Refresh JS
        echo '<script>window.location.reload()</script><a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
             ,$url, '">', $msg, '</a>';
    }

    public function actResolve($act, $resolveAction=null, $resolveController=null, $resolveModule=null, $resolveParams=null,$redirect=true) {
        $rq = $this->_request;

        if($rq->isPost() && $rq->getParam($act)) {
            // Parameters
                if(null === $resolveParams) {
                    $resolveParams = $rq->getParams();
                }

            if($redirect) {
                $this->_helper->redirector($resolveAction, $resolveController, $resolveModule, $resolveParams);
            } else {
                $this->_forward($resolveAction, $resolveController, $resolveModule, $resolveParams);
            }
        }
        return $this;
    }

    public function deserializeParam($field, $delimiter=null) {
        return Apps_View_Helper_SerializeParam::deserializeParam($field, $delimiter);
    }

    /* NO ACTION FOUND */
    public function __call($method, $args) {
    	if('Action' == substr($method, -6)) {
 //   		$this->_redirect('/');
    	}
    }
}